<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2017/12/12
  Time: 17:42
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>客户订单</title>
    <jsp:include page="../headPage.jsp"></jsp:include>
    <script type="text/javascript">

    function toastrStyle(){
    	toastr.options = {
                "closeButton": false,
                "debug": false,
                "newestOnTop": false,
                "progressBar": false,
                "positionClass": "toast-top-center",
                "preventDuplicates": false,
                "onclick": null,
                "showDuration": "5000",
                "hideDuration": "1000",
                "timeOut&quot": "100000",
                "extendedTimeOut": "0",
                "showEasing": "swing",
                "hideEasing": "linear",
                "showMethod": "fadeIn",
                "hideMethod": "fadeOut"
            }; 
    }
    
        $(function () {

            //1.初始化Table
            var oTable = new TableInit();
            oTable.Init();

            //2.初始化Button的点击事件
            var oButtonInit = new ButtonInit();
            oButtonInit.Init();

            //行点击事件
            $('#tb_departments').on('click-row.bs.table', function (e, row, element) {initBottomTable(row.id);});

        });


        var TableInit = function () {
            var oTableInit = new Object();
            //初始化Table
            oTableInit.Init = function () {
                $('#tb_departments').bootstrapTable({
                    url: '${pageContext.request.contextPath }/yzl/customerOrderList.do',         //请求后台的URL（*）
                    method: 'post',                      //请求方式（*）
                    contentType:"application/x-www-form-urlencoded; charset=UTF-8",
                    toolbar: '#toolbar',                //工具按钮用哪个容器
                    //striped: true,                      //是否显示行间隔色
                    cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                    pagination: true,                   //是否显示分页（*）
                    //sortable: false,                     //是否启用排序
                    //sortOrder: "asc",                   //排序方式
                    queryParams: oTableInit.queryParams,//传递参数（*）
                    sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
                    pageNumber: 1,                       //初始化加载第一页，默认第一页
                    pageSize: 10,                       //每页的记录行数（*）
                    pageList: [10, 20, 30],        //可供选择的每页的行数（*）
                    //strictSearch: true,
                    //singleSelect : true, // 单选checkbox
                    maintainSelected: false,
                    minimumCountColumns: 2,             //最少允许的列数
                    //clickToSelect: true,                //是否启用点击选中行
                    height: 400,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
                    columns: [
                        [{
                        checkbox: true
                    },{
                        field: 'id',
                        visible : false
                    }, {
                        field: 'orderNumber',
                        title: '计划单号'
                    }, {
                        field: 'demandDate',
                        title: '计划日期'
                    }, {
                        field: 'customerName',
                        title: '客户'
                    }, {
                        field: 'produceStatus',
                        title: '生产状态',
                        formatter: function (value, row, index) {
                            if (value == 0) {
                                return '未生产'
                            } else if (value == 1) {
                                return '已做计划'
                            } else if (value == 2) {
                                return '已排产'
                            } else if (value == 3) {
                                return '生产中'
                            } else if (value == 4) {
                            	return '生产完成'
                            } else if (value == 5) {
                            	return '排产中'
                            } else {
                            	return 'WTF'
                            }
                        }
                    }, {
                        field: 'outLibraryStatus',
                        title: '出库状态',

                        formatter: function (value, row, index) {
                            if (value == 0) {
                                return '未出库'
                            } else if (value == 1) {
                                return '出库中'
                            } else if (value == 2){
                                return '已出库'
                            } else {
                            	return 'WTF'
                            }
                        }
                    }, {
                        field: 'orderExamineStatus',
                        title: '审批状态',
                        formatter: function (value, row, index) {
                            var back = index;
                            if (value == "0") {
                                return '未提交'
                            } else if (value == "1") {
                                return '审批中'
                            } else if (value == "2") {
                                return '审批完成'
                            } else if (value == "3") {
                                return '审批未通过'
                            } else {
                                return 'WTF'
                            }
                        }
                    }
                    ]
                    ]
                });
            };

            //得到查询的参数
            oTableInit.queryParams = function (params) {
            	//console.log(params);
            	var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
                    limit: params.limit,   //页面大小
                    offset: params.offset / params.limit + 1,  //页码
                    recent: $("#recent").val(),
                    beginDate: $("#beginDate").val(),
                    endDate: $("#endDate").val(),
                    customerName: $("#customerName").val(),
                };
                return temp;
            };
            return oTableInit;
        };


        var ButtonInit = function () {

            var oInit = new Object();
            var postdata = {};

            oInit.Init = function () {
                //初始化页面上面的按钮事件
            };
            return oInit;
        };
        $(function() {
        	//执行后台
            $.ajax({
                url: "${pageContext.request.contextPath}/hpf/customerAllList.do",
                type: "post",
                success: function (data) {
                	//var row = data.rows;
                	for(var i=0;i<data.length;i++){
                    	console.log(data[i]);
                		//添加option
                    	$("#customerName").append("<option>" + data[i].name + "</option>");
                	}
                }
            })
		})
    </script>
</head>
<body>

	<div class="panel-body" style="padding-bottom:0px;">

    	<!--   查询条件  -->
    
	    <div class="panel panel-default">
	    	<div class="panel-heading">查询条件</div>
	        <div class="panel-body">
	            <form id="formSearch" class="form-horizontal">
	                    <label class="control-label col-sm-1">日期:</label>
	                    <div class="col-sm-2">
	                        <select id="recent" name="recent"
	                                class="selectpicker show-tick form-control" data-live-search="false">
	                            <option value="0">所有时间</option>
	                            <option value="1">最近一天</option>
	                            <option value="7">最近一星期</option>
	                            <option value="30">最近一个月</option>
	                        </select>
	                    </div>
	                    <label class="control-label col-sm-1" for="beginDate" style="width: 30px;">从</label>
	                    <div class="col-sm-2">
	                        <input type="text" name="beginDate" id="beginDate" placeholder="yyyy-mm-dd" class="form_datetime form-control">
	                    </div>
	                    <label class="control-label col-sm-1" for="endDate" style="width: 30px;padding-left: 0px;">至</label>
	                    <div class="col-sm-2" style="padding-left: 0px;">
	                        <input type="text" name="endDate" id="endDate" placeholder="yyyy-mm-dd" class="form_datetime form-control">
	                    </div>
	                    <label class="control-label col-sm-1" for="customerName">相关客户:</label>
	                    <div class="col-sm-1">
	                        <select id="customerName" name="customerName"
	                                class="selectpicker show-tick form-control">
	                            <option>所有客户</option>
	                            
	                        </select>
	                    </div>
	                    <div class="col-sm-1">
	                        <button type="button" id="btn_query" class="btn btn-primary">查询</button>
	                    </div>
	                    <!-- <div class="col-sm-1">
	                        <button type="button" id="btn_query1" class="btn btn-default">清除</button>
	                    </div> -->
	                <%--</div>--%>
	            </form>
	        </div>
	    </div>

	    <!--  新增 ==按钮列表  -->
	    <div id="toolbar" class="btn-group">
	        <button id="btn_add" type="button" class="btn btn-default">
	            <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增
	        </button>
	        <button id="btn_edit" type="button" class="btn btn-default">
	            <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>修改
	        </button>
	        <button id="btn_delete" type="button" class="btn btn-default">
	            <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除
	        </button>
	        <!-- <button id="btn_produce" type="button" class="btn btn-default">
	            <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>生产
	        </button> -->
	        <button id="btn_approved" type="button" class="btn btn-default">
	            <span class="glyphicon glyphicon-phone" aria-hidden="true"></span>审批
	        </button>
	        <button id="btn_Undoapproved" type="button" class="btn btn-default">
	            <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>撤销审批
	        </button>
	        <button id="btn_Export" type="button" class="btn btn-default">
	            <span class="glyphicon glyphicon-inbox" aria-hidden="true"></span>导出
	        </button>
	    </div>

	    <!--        表格           -->
	    <table id="tb_departments" style="font-size: 14px;"></table>
	
	    <!--    底部详情表格   -->
	    <div id="bottomTableDiv" style="font-size: 14px;"></div>
	
	    <!--          修改表单       -->
	    <div class="modal fade" id="updateNumberModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
	        <div class="modal-dialog" style="width: 70%;height: 60%">
	            <div class="modal-content">
	                <div class="modal-header">
	                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
	                    <h4 class="modal-title" id="updateModalLabel">新增订单</h4>
	                </div>
	
	                <input hidden="hidden" id="updateCustomerId">
	                <input hidden="hidden" id="updateOrderNumId">
	                <div id="updateModelTable_outDiv"></div>
	
	                <div class="modal-footer">
	                    <button type="button" class="btn btn-primary" style="float:left" id="btn_updateIn">添加产品</button>
	                    <button type="button" class="btn btn-primary" style="float:left">删除产品</button>
	                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
	                    <button type="button" class="btn btn-primary" id="btn_update">确定</button>
	                </div>
	            </div><!-- /.modal-content -->
	        </div><!-- /.modal-dialog -->
	    </div>
	
	    <!--          添加表单       -->
	    <div class="modal fade" id="addNumberModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
	        <div class="modal-dialog" style="width: 70%;height: 60%">
	            <div class="modal-content">
	                <div class="modal-header">
	                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
	                    <h4 class="modal-title" id="myModalLabel">新增订单</h4>
	                </div>
	
	                <input hidden="hidden" id="customerId">
	
	                <div id="addModelTable_outDiv"></div>
	
	                <div class="modal-footer">
	                    <button type="button" class="btn btn-primary" style="float:left" id="btn_addIn">添加产品</button>
	                    <button type="button" class="btn btn-primary" style="float:left">删除产品</button>
	                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
	                    <button type="button" class="btn btn-primary" id="btn_save">确定</button>
	                </div>
	            </div><!-- /.modal-content -->
	        </div><!-- /.modal-dialog -->
	    </div>
	
	    <!--          客户选择表单       -->
	    <div class="modal fade" id="customerModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
	        <div class="modal-dialog" style="width: 60%;height: 50%">
	            <div class="modal-content">
	                <div class="modal-header">
	                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
	                    <h4 class="modal-title" id="customerModalLabel">新增订单</h4>
	                </div>
	
	                <table id="td_customerTable"></table>
	
	                <div class="modal-footer">
	                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
	                    <button type="button" class="btn btn-primary" onclick="backCus()" id="backCus">确定</button>
	                </div>
	            </div><!-- /.modal-content -->
	        </div><!-- /.modal-dialog -->
	    </div>
	
	    <!--          客户选择表单       -->
	    <div class="modal fade" id="proListModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
	        <div class="modal-dialog" style="width: 60%;height: 50%">
	            <div class="modal-content">
	                <div class="modal-header">
	                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
	                    <h4 class="modal-title" id="proListModalLabel">新增订单</h4>
	                </div>
	
	                <table id="td_proListTable"></table>
	
	                <div class="modal-footer">
	                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
	                    <button type="button" class="btn btn-primary" onclick="backPro()" id="backPro">确定</button>
	                </div>
	            </div><!-- /.modal-content -->
	        </div><!-- /.modal-dialog -->
	    </div>
	
	
	    <!--    删除   -->
	    <div class="modal fade" id="myModalDelete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
	        <div class="modal-dialog" style="width: 40%;height: 50%">
	            <div class="modal-content">
	                <div class="modal-header">
	                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
	                    <h4 class="modal-title" id="myModalDeleteLabel">删除确认</h4>
	                </div>
	
	
	
	                <div class="modal-footer">
	                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
	                    <button type="button" class="btn btn-primary" onclick="deleteOrder()">确定删除</button>
	                </div>
	            </div><!-- /.modal-content -->
	        </div><!-- /.modal-dialog -->
	    </div>
	    
	</div>

    <script>

        $(function (){
            $("#btn_Undoapproved").click(function (){Undoapproved()});
        })

        //点击保存新增订单
        $("#btn_save").click(function () {
            //得到原来的表格数据
            var allTableData = $('#td_addModelTable').bootstrapTable('getData');//获取表格的所有内容行
            //循环将填写的数量填入表格
            for(var i=0;i<allTableData.length;i++){
                var count = $("#addTIndex"+allTableData[i].id).val();
                allTableData[i].planQ = count;
                allTableData[i][0] = undefined;
            }
            //得到选择的客户ID
            var customerId = $("#customerId").val();
            var obj = dedaoValue("td_addModelTable");
            var obj1 = {
                number : obj.number,
                customerId : customerId,
                planDate : obj.time,
                productors : allTableData
            };
            $.ajax({
                url : "${pageContext.request.contextPath }/yzl/addFrom.do",
                type : "POST",
                data : JSON.stringify(obj1),
                contentType: "application/json; charset=utf-8",
                dataType : "json",
                success : function(data){
                    if(data == 1){
                    	toastrStyle();
                    	toastr.warning("保存成功！");
                        //关闭模态框
                        $("#addNumberModal").modal('hide');
                        //$("#btn_save").attr("data-dismiss","modal");
                    }else{
                    	toastrStyle();
                    	toastr.warning("保存失败！");
                    }
                }
            })

        })

        $("#btn_query").click(function (){refreshAjax();})

        //清除输入的条件
        $("#btn_query1").click(function (){$("#beginDate").val("");$("#endDate").val("");})

        $("#btn_delete").click(function () {

            //必须选中一条数据
        	var checkedItems = $('#tb_departments').bootstrapTable('getSelections');
            if(checkedItems <= 0){
            	toastrStyle();
                toastr.warning('请选择一行信息');
            }else{
                console.log("checkedItems----",checkedItems);
                var arr = filteDataApproval2(checkedItems);
                if (arr) {
            		//询问框
            		Ewin.confirm({message : "确认要删除选择的数据吗？"}).on(
            			function(e) {
            				if (!e) {return;}
            				$.ajax({
                                url: "${pageContext.request.contextPath}/yzl/deleteOrder.do",
                                type: "post",
                                data: {"arr": JSON.stringify(arr)},
                                success: function (data) {
                                    if (data != 0) {
                                    	toastrStyle();
                                        toastr.success('删除成功');
                                        refreshAjax();
                                    } else {
                                    	toastrStyle();
                                        toastr.warning('删除失败');
                                    }
                                }
                            })
            			});
                } else {
                	toastrStyle();
                	toastr.warning('只能删除未审批的销售计划');
                }
            }
        });

        function deleteOrder(){

            var checkedItems = $('#tb_departments').bootstrapTable('getSelections');
            //var checkedItem = checkedItems[0];
            $("#myModalDelete").modal('hide');
            //comAjax("${pageContext.request.contextPath}/yzl/deleteOrder.do",{id:list},function(data){})
            var arr1 = filteDataApproval2(checkedItems);
            /* if (arr1) {
            	var arr2 = filterOutData(checkedItems);
                if (arr2) {
                    //执行后台 */
                    
              /*   }
            } */
            window.location.href = "${pageContext.request.contextPath }/pages/yzlERP/salesPlan/salesPlan.jsp";
        }

        //提交审核
        $("#btn_approved").click(function () {
            //必须选中一条数据
            var checkedItems = $('#tb_departments').bootstrapTable('getSelections');
            var checkedItem = checkedItems[0];
            if (checkedItems <= 0) {
            	toastrStyle();
                toastr.warning('请选择一行信息');
            } else {
                var arr1 = filteDataApproval2(checkedItems);
                if (arr1) {
                	//执行后台
                    $.ajax({
                    	url: "${pageContext.request.contextPath}/yzl/orderApproveds.do",
                        type: "post",
                        data: {"arr": JSON.stringify(arr1)},
                        success: function (data) {
                        	if (data != 0) {
                        		toastrStyle();
                            	toastr.success('审批成功');
                                refreshAjax();
                            } else {
                            	toastrStyle();
                                toastr.warning('审批失败');
                            }
                        }
                    })
                } else {
                	toastrStyle();
                	toastr.warning('只能选择未审批的信息记录');
                }
            }
        });

        //撤销审核
        function Undoapproved(){
            //必须选中一条数据
            var checkedItems = $('#tb_departments').bootstrapTable('getSelections');
            var checkedItem = checkedItems[0];
            if (checkedItems <= 0) {
            	toastrStyle();
                toastr.warning('请选择一行信息');
            } else {
                var arr = filterDataUn(checkedItems);
                if (arr) {
                    //执行后台
                    $.ajax({
                        url: "${pageContext.request.contextPath}/yzl/orderUnApproveds.do",
                        type: "post",
                        data: {"arr": JSON.stringify(arr)},
                        success: function (data) {
                            if (data != 0) {
                            	toastrStyle();
                                toastr.success('撤销成功');
                                refreshAjax();
                            } else {
                            	toastrStyle();
                                toastr.warning('撤销失败');
                            }
                        }
                    })
                } else {
                	toastrStyle();
                    toastr.warning('只能选择审批中的信息');
                }
            }
        }
        
      	//导出
        $("#btn_Export").click(function () {
        	//询问框
    		Ewin.confirm({message : "确认要导出所有数据吗？"}).on(
    			function(e) {
    				if (!e) {return;}
    				window.location.href="${pageContext.request.contextPath}/yzl/orderExport.do"
    			});
        });

        $("#btn_addIn").click(function (){initProductorsTable();})

        //选择客户
        function choseCustomer(){initCustomerTable()}

        //选择客户 返回带回数据 关闭第二层模态框 第一层模态框表格重新加载
        function backCus(){

            //得到修改的ID
            var orderId = $("#updateOrderNumId").val();
            //得到选择的数据
            var rows = $('#td_customerTable').bootstrapTable('getSelections')[0];
            //得到原来的表头信息
            var objTable = dedaoValue("td_addModelTable");
            if(rows){
                //关闭第二层模态框
                $("#backCus").attr("data-dismiss","modal");
                //更新第一层模态框的表格
                initAddTable(objTable.number,objTable.time,rows.name,rows.name,"1111",rows.name,orderId);
                //给customerId赋值
                $("#customerId").val(rows.id);
                //给updateCustomerId赋值
                $("#updateCustomerId").val(rows.id);
            }else{
            	toastrStyle();
            	toastr.warning("请选择客户");
            }
        }

        //选择产品
        function backPro(){
            //得到修改的ID
            var orderId = $("#updateOrderNumId").val();
            //得到选择的数据
            var rows = $('#td_proListTable').bootstrapTable('getSelections');
            //得到原来的表格数据
            var allTableData = $('#td_addModelTable').bootstrapTable('getData');//获取表格的所有内容行
            for(var j=0;j<rows.length;j++){
                allTableData.push(rows[j]);
            }
            //得到原来的表头信息
            var objTable = dedaoValue("td_addModelTable");
            if(rows){
                //关闭第二层模态框
                $("#backPro").attr("data-dismiss","modal");
                //更新第一层模态框的表格
                initAddTable(objTable.number,objTable.time,rows.name,objTable.customer,"1111",rows.name,orderId);

                for(var i=0;i<allTableData.length;i++){
                    for(var x = 0;x<rows.length;x++){
                        if(rows[x].id != allTableData[i].id){
                            $('#td_addModelTable').bootstrapTable('insertRow', {
                                index:$('#td_addModelTable').bootstrapTable('getOptions').totalRows,
                                row:allTableData[i]
                            });
                        }
                    }
                }


            }else{
            	toastrStyle();
            	toastr.warning("请选择客户");
            }
        }

    //关闭计划
    function closePlan(index) {
        var id = $("#tb_departments").bootstrapTable('getData')[index].id;
        $.ajax({
            url: "${pageContext.request.contextPath}/yzl/closePlan.do",
            type: "post",
            data: {"id": id},
            success: function (data) {
                if (data != 0) {
                    toastr.info('操作成功');
                    refreshAjax();
                } else {
                    toastr.warning('操作失败');
                }
            }
        })
    }


    //添加产品
    function addPro(index) {

        $("#customerOrdId").val($("#tb_departments").bootstrapTable('getData')[index].id);

        $('#tb_listPro').bootstrapTable({
            //url: '/pages/yzl/data/customerOrder.json',         //请求后台的URL（*）
            url: '${pageContext.request.contextPath }/yzl/productorList.do',         //请求后台的URL（*）
            method: 'post',                      //请求方式（*）
            striped: true,                      //是否显示行间隔色
            queryParamsType: "limit",
            sortOrder: "asc",                   //排序方式
            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
            strictSearch: true,
            showColumns: true,                  //是否显示所有的列
            //showRefresh: true,                  //是否显示刷新按钮
            minimumCountColumns: 2,             //最少允许的列数
            //clickToSelect: true,                //是否启用点击选中行
            height: 500,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
            uniqueId: "ID",                     //每一行的唯一标识，一般为主键列
            cardView: false,                    //是否显示详细视图
            detailView: false,                   //是否显示父子表
            columns: [{
                checkbox: true
            }, /*{
                        field: 'id',
                        title: 'ID'
                    },*/ {
                field: 'pm',
                title: '品名'
            }, {
                field: 'pb',
                title: '品编'
            }, {
                field: 'add',
                title: '添加',
                formatter: function (value, row, index) {
                    return '<a href="#" onclick="addToCusOrder()">添加</a>'
                }
            }]
        });

        $('#listPro').modal({
            keyboard: true,
        })

    }

    //将产品添加至销售计划中
    function addToCusOrder() {}

    //选中数据条件筛选（审批判断）
    function filteDataApproval1(checkedItems){
        var arr = new Array();
        for (var i = 0; i < checkedItems.length; i++) {
            var produceStatus = checkedItems[i].produceStatus;
            if (produceStatus != "2") {
                return false
            } else {
                arr.push(checkedItems[i].id);
            }
        }
        return arr;
    }
    
    function filteDataApproval2(checkedItems){
        var arr = new Array();
        for (var i = 0; i < checkedItems.length; i++) {
            var orderExamineStatus = checkedItems[i].orderExamineStatus;
            if (orderExamineStatus != "0") {
                return false
            } else {
                arr.push(checkedItems[i].id);
            }
        }
        return arr;
    }
    
    //选中数据条件筛选（撤销审批）
    function filterDataUn(checkedItems){
        var arr = new Array();
        for (var i = 0; i < checkedItems.length; i++) {
            var orderExamineStatus = checkedItems[i].orderExamineStatus;
            if (orderExamineStatus != "1") {
                return false
            } else {
                arr.push(checkedItems[i].id);
            }
        }
        return arr;
    }

    //选中数据条件筛选（是否生产）
    function filterData(checkedItems) {
        var arr = new Array();
        for (var i = 0; i < checkedItems.length; i++) {
            var produceStatus = checkedItems[i].produceStatus;
            if (produceStatus == "2" || produceStatus == "1") {
                return false
            } else {
                arr.push(checkedItems[i].id);
            }
        }
        return arr;
    }

    function makeRequirement() {
        $('#requirementModel').modal({
            keyboard: true,
        })
    }

    function tiJiao() {
        $('#layui-layer20').modal({
            keyboard: true,
        })
    }


    //统一请求ajax
    function comAjax(url,data,fuc){
        $.ajax({
            type:"POST",
            url:url,
            data:data,
            success:function (data) {
                fuc(data);
            },
        })
    }
    //点击查询 重新请求  刷新表格
    function refreshAjax() {
        $("#tb_departments").bootstrapTable('refresh', {url: '${pageContext.request.contextPath }/yzl/customerOrderList.do'});
    }
</script>

<!--      表格初始化     -->
<script>

    //添加表格初始化
    function initAddTable(number,time,zhidanMan,customer,beforeNumber,approvedMan,id,modalId){
        var $addModelTable_outDiv = $("#addModelTable_outDiv");
        if($addModelTable_outDiv.find("table").length > 0){
            $addModelTable_outDiv.empty();
        }
        var table = '<table id="td_addModelTable"></table>'
        $addModelTable_outDiv.append(table);

        /*var listH = '<div class="modal-footer">\n' +
            '                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>\n' +
            '                    <button type="button" class="btn btn-primary" onclick="deleteOrder()">确定删除</button>\n' +
            '                </div>'

        $addModelTable_outDiv.append(listH);*/

        if(time == "" || time == null){
            time = '<input type="text" name="addTime" id="addTime" lay-verify="date"\n' +
                '                               placeholder="yyyy-mm-dd"\n' +
                '                               autocomplete="off" class="layui-input form-control"\n' +
                '                               onclick="layui.laydate({elem: this})">'
        }else{
            time = '<input type="text" name="addTime" id="addTime" lay-verify="date"\n' +
                '                               placeholder='+time+'\n' +
                '                               autocomplete="off" class="layui-input form-control"\n' +
                '                               onclick="layui.laydate({elem: this})" value="'+time+'">'
        }
        if(customer == "" || customer == null){
            customer = '<a href="#" onclick="choseCustomer()">选择客户</a>';
        }else{
            customer = '<a href="#" onclick="choseCustomer()">'+customer+'</a>';
        }

        newurl = "";
        if(id != "" || id !== null){
            newurl = "${pageContext.request.contextPath }/yzl/customerOrderXq.do?id="+id;
        }

        $('#td_addModelTable').bootstrapTable({
            dataType: "json",
            method: 'get',
            contentType: "application/x-www-form-urlencoded",
            cache: false,
            toolbar: '#toolbarIn',
            url : newurl,
            columns: [
                [
                    {
                        field: 'name',
                        title: "销售计划单",
                        valign: "middle",
                        align: "center",
                        colspan: 1
                    },
                    {
                        title: number,
                        valign: "middle",
                        align: "center",
                        colspan: 1,
                    },
                    {
                        title: '计划时间',
                        valign: "middle",
                        align: "center",
                        colspan: 2,
                    },
                    {
                        title: time,
                        valign: "middle",
                        align: "center",
                        colspan: 1,
                    },
                    {
                        title: "指定人",
                        valign: "middle",
                        align: "center",
                        colspan: 1,
                    },
                    {
                        title: zhidanMan,
                        valign: "middle",
                        align: "center",
                        colspan: 1,
                    }
                ],
                [
                    {
                        field: 'name',
                        title: "客户",
                        valign: "middle",
                        align: "center",
                        colspan: 1
                    },
                    {
                        title: customer,
                        valign: "middle",
                        align: "center",
                        colspan: 4,
                    },
                    {
                        title: "审批人",
                        valign: "middle",
                        align: "center",
                        colspan: 1,
                    },
                    {
                        title: approvedMan,
                        valign: "middle",
                        align: "center",
                        colspan: 1,
                    },
                ],
                [
                    {
                        field: 'cartype',
                        title: '车种',
                        valign: "middle",
                        align: "center"
                    },
                    {
                        field: 'num',
                        title: '品编',
                        valign: "middle",
                        align: "center"
                    },
                    {
                        field: 'name',
                        title: '品名',
                        valign: "middle",
                        align: "center"
                    },
                    {
                        field: 'planQ',
                        title: '计划数量',
                        valign: "middle",
                        align: "center",
                        formatter: function (value, row, index) {
                            if(row.planQ > 0){
                                return '<input type="text" class="form-control" id="addTIndex'+row.id+'" value="'+row.planQ+'">'
                            }else{
                                return '<input type="text" class="form-control" id="addTIndex'+row.id+'">'
                            }
                            //return '<input type="text" class="form-control" value="'+row.outQ+'">'

                        }
                    },
                    {
                        field: 'remark8',
                        title: '单价',
                        valign: "middle",
                        align: "center"
                    },
                    {
                        field: 'amount',
                        title: '金额',
                        valign: "middle",
                        align: "center"
                    },
                    {
                        field: 'dayConsumptionQ',
                        title: '日消耗量',
                        valign: "middle",
                        align: "center"
                    }

                ]
            ]
        });
        $('#addNumberModal').modal({keyboard: true,});

        //$('#'+modalId).modal({keyboard: true,});
        //$("#toolbarIn").css("display","block");

    }

    //初始化客户表单
    function initCustomerTable(){
        $('#td_customerTable').bootstrapTable({
            dataType: "json",
            method: 'get',
            contentType: "application/x-www-form-urlencoded",
            cache: false,
            singleSelect : true, // 单选checkbox
            //url: "/pages/yzlERP/data/customerList.json",
            url: "${pageContext.request.contextPath }/yzl/customerList.do",
            columns: [
                [
                    { checkbox: true },
                    {
                        field: 'name',
                        title: "名称",
                        valign: "middle",
                        align: "center"
                    },
                    {
                        field:"age",
                        title: "年龄",
                        valign: "middle",
                        align: "center"
                    }
                ]
            ]
        });
        $("#customerModal").modal({keyboard: true,})
    }

    //初始化产品表单
    function initProductorsTable(){
        $('#td_proListTable').bootstrapTable({
            dataType: "json",
            method: 'get',
            contentType: "application/x-www-form-urlencoded",
            cache: false,
            clickToSelect: true,    //是否启用点击选中行
            //singleSelect : true, // 单选checkbox
            //: "/pages/yzlERP/data/
            url: "${pageContext.request.contextPath }/yzl/carList.do",
            columns: [
                [
                    { checkbox: true },
                    {
                        field: 'cartype',
                        title: "车种",
                        valign: "middle",
                        align: "center"
                    },
                    {
                        field:"name",
                        title: "品名",
                        valign: "middle",
                        align: "center"
                    },
                    {
                        field:"num",
                        title: "品编",
                        valign: "middle",
                        align: "center"
                    }
                ]
            ]
        });
        $("#proListModal").modal({keyboard: true,})
    }

    //底部详情列表初始化
    function initBottomTable(id){
        var $bottomTableDiv = $("#bottomTableDiv");
        if($bottomTableDiv.find("table").length > 0){
            url = "${pageContext.request.contextPath }/yzl/customerOrderXq.do?id="+id;
            $("#tb_details").bootstrapTable('refresh', {url: url});
            //$bottomTableDiv.empty();
        }else{
            var table = '<table id="tb_details"  style="font-size: 14px;"></table>'
            $bottomTableDiv.append(table);
        }

        $('#tb_details').bootstrapTable({
            dataType: "json",
            method: 'get',
            contentType: "application/x-www-form-urlencoded",
            cache: false,
            height: 300,
            toolbar: '#toolbarIn',
            url: "${pageContext.request.contextPath }/yzl/customerOrderXq.do?id="+id,
            columns: [
                [
				{
				    checkbox: true
				},
                    {
                        field: 'cartype',
                        title: '车种',
                        valign: "middle",
                        align: "center"
                    },
                    {
                        field: 'num',
                        title: '品编',
                        valign: "middle",
                        align: "center"
                    },
                    {
                        field: 'name',
                        title: '品名',
                        valign: "middle",
                        align: "center"
                    },
                    {
                        field: 'planQ',
                        title: '计划数量',
                        valign: "middle",
                        align: "center"
                    },
                    {
                        field: 'remark8',
                        title: '单价',
                        valign: "middle",
                        align: "center"
                    },
                    {
                        field: 'amount',
                        title: '金额',
                        valign: "middle",
                        align: "center",
                        formatter: function (value, row, index) {
                            return accMul(row.planQ,row.remark8);
                        }
                    },
                    {
                        field: 'finishDate',
                        title: '计划完成日期',
                        valign: "middle",
                        align: "center"
                    }/* ,
                    {
                        field: 'dayConsumptionQ',
                        title: '日消耗量',
                        valign: "middle",
                        align: "center"
                    } */

                ]
            ]
        });



    }

    //根据传入的表格ID 查询数据
    function dedaoValue(tableId){

        //拿到原来表格中填写的订单号和时间
        var $thead  = $($($("#"+tableId)[0]).find("thead")[0]);
        //拿到第一行
        var $tr1 = $($thead.find("tr")[0]);
        //拿到订单号
        var number = $($($tr1.find("th")[1]).find("div")[0]).text();
        //拿到时间
        var time = $("#addTime").val();


        //拿到第二行
        var $tr2 = $($thead.find("tr")[1]);
        //拿到客户名称
        var customer = $($($tr2.find("th")[1]).find("div")[0]).text();
        console.log("customer--",customer);
        var obj = {
            number : number,
            time : time,
            customer : customer
        };
        return obj;
    }
</script>

<!--  时间插件   -->
<script>
    layui.use(['form', 'layedit', 'laydate'], function () {
        var form = layui.form(),
            layer = layui.layer,
            layedit = layui.layedit,
            laydate = layui.laydate;

        //创建一个编辑器
        var editIndex = layedit.build('LAY_demo_editor');
        //自定义验证规则
        form.verify({
            title: function (value) {
                if (value.length < 5) {
                    return '标题至少得5个字符啊';
                }
            },
            pass: [/(.+){6,12}$/, '密码必须6到12位'],
            content: function (value) {
                layedit.sync(editIndex);
            }
        });

        //监听提交
        form.on('submit(demo1)', function (data) {
            layer.alert(JSON.stringify(data.field), {
                title: '最终的提交信息'
            })
            return false;
        });
    });

</script>
<script type="text/javascript">
 $(function () {
	$(".form_datetime").datetimepicker({
	 format: "yyyy-mm-dd",
	 autoclose: true,
	 todayBtn: true,
	 todayHighlight: true,
	 showMeridian: true,
	 pickerPosition: "bottom-left",
	 language: 'zh-CN',//中文，需要引用zh-CN.js包
	 startView: 2,//月视图
	 minView: 2//日期时间选择器所能够提供的最精确的时间选择视图
	 });
 });
</script>
<!-- <script type="text/javascript" src="plugins/layui/layui.js"></script> -->
<script>
        //循环获取父层的tab对象，为什么用循环呢？因为子层加载完，父层还不一定加载完了。所以获取到的是undefined
        /*var index = setInterval(function() {
            if(typeof parent.tab !== 'undefined') {
                //如果获取到tab对象，则停止循环
                clearInterval(index);
                //通过调用父层的tab组件里的tabAdd方法添加一个tab选项卡
                parent.tab.tabAdd({
                    href: 'https://www.baidu.com', //地址
                    icon: 'fa-user',
                    title: '这是在子窗口打开的tab选项卡'
                });
            }
        }, 20);*/
        //如果需要在些页面上获取到父页面的变量，需要把变量设置为全局，
        /**
         * 例：
         * var tab;
         * layui.use('tab',function(){
         * 	   tab = layui.tab(setting);
         * });
         */
        //上面那个是页面渲染完就添加的
        layui.use(['layer'], function () {
            var aa = 111;
            var $ = layui.jquery,
                layer = layui.layer;

            //移除当前的选项卡
            $('#remove').on('click', function () {
                var tab = parent.tab;

                tab.deleteTab(tab.getCurrentTabId());
            });

            //这个是点击之后才添加的。
            $('#btn_add').on('click', function () {

                window.location.href = "${pageContext.request.contextPath}/pages/yzlERP/salesPlan/add.jsp";

                //这是核心的代码。
                /*parent.tab.tabAdd({
                    href: "/pages/yzlERP/salesPlan/add.jsp", //地址
                    icon: "",
                    title: "添加"
                });*/
            });
            $('#btn_edit').on('click', function () {

                //必须选中一条数据
                var checkedItems = $('#tb_departments').bootstrapTable('getSelections');
                var checkedItem = checkedItems[0];
				console.log(checkedItems.length);
                if(checkedItems.length == 0){
                	toastrStyle();
                    toastr.warning('请选择一行信息');
                }else if(checkedItems.length == 1){
                	if(checkedItem.orderExamineStatus!='0'){
                		toastrStyle();
                		toastr.warning('只能修改未审批的计划记录');
                	}else{
                		window.location.href = "${pageContext.request.contextPath}/pages/yzlERP/salesPlan/update.jsp?id="+checkedItem.id;
                	}
                } else{
                	toastrStyle();
                	toastr.warning('每次只能修改一条信息');
                }


            });

        });
    </script>
</body>
</html>
